package com.cy.store.controller;

import com.cy.store.controller.ex.*;
import com.cy.store.service.ex.*;
import com.cy.store.util.JsonResult;
import org.springframework.web.bind.annotation.ExceptionHandler;

import javax.servlet.http.HttpSession;

/**
 * @author ZhangSir
 */
public class BaseController {

    public static final Integer OK = 200;

    // 请求处理方法，这个方法的返回值就是要返回给前端的数据
    // 自动将异常对象传递给此方法的参数列表上
    // 当前项目中产生了异常，被统一拦截到此方法中，这个方法此时就是充当请求处理方法，方法的返回值直接给到前端
    @ExceptionHandler({ServiceException.class,FileUploadException.class})
    public JsonResult<Void> handleException(Throwable e) {
        JsonResult<Void> result = new JsonResult<>(e);
        if (e instanceof UsernameDuplicatedException) {
            result.setCode(4000);
            result.setMessage("该用户名已经被注册");
        } else if (e instanceof InsertException) {
            result.setCode(5000);
            result.setMessage("服务器发生异常,注册失败");
        } else if (e instanceof UserNotFoundException) {
            result.setCode(4001);
            result.setMessage("未找到该用户，该用户未注册");
        } else if (e instanceof PasswordNotMatchException) {
            result.setCode(4002);
            result.setMessage("密码错误");
        } else if (e instanceof UpdateException) {
            result.setCode(4003);
            result.setMessage("修改时发生异常");
        } else if (e instanceof FileEmptyException) {
            result.setCode(6000);
            result.setMessage("文件为空");
        } else if (e instanceof FileSizeException) {
            result.setCode(6001);
            result.setMessage("文件大小超出限制");
        } else if (e instanceof FileTypeException) {
            result.setCode(6002);
            result.setMessage("文件类型错误");
        } else if (e instanceof FileUploadIoException) {
            result.setCode(6003);
            result.setMessage("文件上传过程中发生异常");
        } else if (e instanceof FileStateException) {
            result.setCode(6004);
            result.setMessage("文件状态不对");
        } else if (e instanceof InsertAddressException) {
            result.setCode(7001);
            result.setMessage("插入时发生未知异常，插入失败");
        } else if (e instanceof AddressCountLimitException) {
            result.setCode(7002);
            result.setMessage("用户收货地址超出上限的异常");
        }
        return result;
    }
    /**
     * 定义一个从session中获取uid，username的方法，并封装到BaseController类中
     * @param session 全局会话
     * @return 将从session中获取到的uid和username返回
     */
    public final Integer getUidFromSession(HttpSession session){
        if (session != null){
            return Integer.valueOf(session.getAttribute("uid").toString());
        }
        return null;
    }

    protected final String getUsernameFromSession(HttpSession session){
        if (session != null){
            return session.getAttribute("username").toString();
        }
        return null;
    }
}
